package com.ruoyi.message.message;

import com.ruoyi.message.notice.NoticeHandshakeInterceptor;
import com.ruoyi.message.notice.NoticeWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;

/**
 * @author huajiao
 * @date 2025/3/18 23:11
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Autowired
    private ChatWebSocketHandler chatHandler;

    @Autowired
    private ChatHandshakeInterceptor handshakeInterceptor;

    @Autowired
    private NoticeWebSocketHandler noticeHandler;

    @Autowired
    private NoticeHandshakeInterceptor noticeHandshakeInterceptor;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(chatHandler, "/ws/chat")
                .addInterceptors(handshakeInterceptor)
                .setAllowedOrigins("*"); // 允许跨域[4](@ref)
        registry.addHandler(noticeHandler, "/ws/notice")
                .addInterceptors(noticeHandshakeInterceptor)
                .setAllowedOrigins("*"); // 允许跨域[4](@ref)
    }

    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer() {
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        container.setMaxBinaryMessageBufferSize(1024 * 1024); // 解决缓冲区不足问题[5](@ref)
        return container;
    }
}